package com.mydemo.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mydemo.common.pojo.LoginUser;
import com.mydemo.common.pojo.RespResult;
import com.mydemo.common.utils.SecurityUtils;
import com.mydemo.common.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

/**
 * @author Last_Island
 * @version 1.0
 */
public class BaseController {
    @Value("${token.header}")
    private String tokenHeader;
    @Value("${token.tokenHead}")
    private String tokenHead;
    /**
     * 开启分页
     */
    public void startPage(){
        HttpServletRequest request = ServletUtils.getHttpServletRequest();
        int pageNum = 1;
        int pageSize = 10;
        String num = request.getParameter("pageNum");
        String size = request.getParameter("pageSize");
        if (StringUtils.hasText(num) && StringUtils.hasText(size)) {
            pageNum = Integer.parseInt(num);
            pageSize = Integer.parseInt(size);
        }
        PageHelper.startPage(pageNum, pageSize).setReasonable(true);
    }

    /**
     * 获取分页数据
     */
    public RespResult getTabData(List<?> list){
        RespResult success = RespResult.success("查询成功");
        success.put("rows", list);
        success.put("total", new PageInfo<>(list).getTotal());
        return success;
    }

    /**
     * 获取当前登录用户
     * @return
     */
    public LoginUser getLoginUser(){
        return SecurityUtils.getLoginUser();
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken(){
        HttpServletRequest request = ServletUtils.getHttpServletRequest();
        String header = request.getHeader(tokenHeader);
        String authToken = header.substring(this.tokenHead.length());// The part after "Bearer "
        return authToken;
    }
}
